package com.ruoyi.system.service.impl;

import java.beans.Transient;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.*;
import com.ruoyi.generator.domain.PersistContext;
import com.ruoyi.generator.domain.ReportSource;
import com.ruoyi.generator.service.IGenWordService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.enums.ArticleStyleEnum;
import com.ruoyi.system.enums.EventOpinionRelationEnum;
import com.ruoyi.system.service.IBriefReportService;
import com.ruoyi.system.service.IGenerateReportService;
import com.ruoyi.system.service.IPoPublicOpinionService;

import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.PublicOpinionEventsMapper;
import com.ruoyi.system.service.IPublicOpinionEventsService;



/**
 * 事件Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-06-08
 */
@Service
public class PublicOpinionEventsServiceImpl implements IPublicOpinionEventsService 
{
    @Autowired
    private PublicOpinionEventsMapper publicOpinionEventsMapper;
    @Autowired
    private IBriefReportService briefReportService;
    @Autowired
    private IGenWordService genWordService;
    @Autowired
    private IGenerateReportService generateReportService;
    @Autowired
    private IPoPublicOpinionService publicOpinionService;
    @Autowired
    private PublicOpinionReportServiceImpl publicOpinionReportService;
    @Autowired
    private EsUtil esUtil;
    @Autowired
    private NlpcUtil nlpcUtil;


    @Value("${phantomjs.savePath}")
    private String phantomjsSavePath;





    @Override
    /**
     * 根据事件获取舆情（绑定库）
     * @param eventId
     * @return
     */
    public List<String> getMatchOpinionByEventIdForDataBase(Long eventId) {
        List<String> bindIds = new ArrayList<>();
        if (eventId != null) {
            PoEventOpinionRelation poEventOpinionRelation = new PoEventOpinionRelation();
            poEventOpinionRelation.setEventId(eventId);
            poEventOpinionRelation.setRelation(EventOpinionRelationEnum.Bind.value);
            bindIds = selectOpinionsByEventRelation(poEventOpinionRelation);
        }
        return bindIds;
    }

    @Override
    public List<String> selectOpinionsByEventRelation(PoEventOpinionRelation poEventOpinionRelation) {
        return publicOpinionEventsMapper.selectOpinionsByEventRelation(poEventOpinionRelation.getEventId(), poEventOpinionRelation.getRelation());
    }


    @Override
    /**
     * 根据事件获取舆情（排除库）
     * @param eventId
     * @return
     */
    public List<String> getExcludeIdsByEventIdForDataBase(Long eventId) {
        List<String> excludeIds = new ArrayList<>();
        if (eventId != null) {
            PoEventOpinionRelation poEventOpinionRelation = new PoEventOpinionRelation();
            poEventOpinionRelation.setEventId(eventId);
            poEventOpinionRelation.setRelation(EventOpinionRelationEnum.Exclude.value);
            excludeIds = selectOpinionsByEventRelation(poEventOpinionRelation);
        }
        return excludeIds;
    }



    /**
     * 查询事件
     * 
     * @param eventId 事件ID
     * @return 事件
     */
    @Override
    public PublicOpinionEvents selectPublicOpinionEventsById(Long eventId)
    {
        return publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
    }

    @Override
    public List<PublicOpinionEvents> selectPublicOpinionEventsByIds(Long[] eventIds) {
        return publicOpinionEventsMapper.selectPublicOpinionEventsByIds(eventIds);
    }

    /**
     * 查询事件列表
     * 
     * @param publicOpinionEvents 事件
     * @return 事件
     */
    @Override
    @DataScope(deptAlias = "event",userAlias = "event")
    public List<PublicOpinionEvents> selectPublicOpinionEventsList(PublicOpinionEvents publicOpinionEvents)
    {
        return publicOpinionEventsMapper.selectPublicOpinionEventsList(publicOpinionEvents);
    }

    /**
     * 新增事件
     * 
     * @param publicOpinionEvents 事件
     * @return 结果
     */
    @Override
    public int insertPublicOpinionEvents(PublicOpinionEvents publicOpinionEvents)
    {
        return publicOpinionEventsMapper.insertPublicOpinionEvents(publicOpinionEvents);
    }

    /**
     * 修改事件
     * 
     * @param publicOpinionEvents 事件
     * @return 结果
     */
    @Override
    public int updatePublicOpinionEvents(PublicOpinionEvents publicOpinionEvents)
    {
        return publicOpinionEventsMapper.updatePublicOpinionEvents(publicOpinionEvents);
    }

    /**
     * 批量删除事件
     * 
     * @param eventIds 需要删除的事件ID
     * @return 结果
     */
    @Override
    public int deletePublicOpinionEventsByIds(Long[] eventIds)
    {
        return publicOpinionEventsMapper.deletePublicOpinionEventsByIds(eventIds);
    }

    /**
     * 删除事件信息
     * 
     * @param eventId 事件ID
     * @return 结果
     */
    @Override
    public int deletePublicOpinionEventsById(Long eventId)
    {
        return publicOpinionEventsMapper.deletePublicOpinionEventsById(eventId);
    }




    private List<ReportSource> buildReportSource(PublicOpinionEvents event,BriefReportVo template,Date startDate,Date endDate,Map<String, String> mapBase64) {
        List<ReportSource> contents = new ArrayList<>();
        if (template.getElements() != null && template.getElements().size() > 0) {
            Date finalEndDate = endDate;
            template.getElements().forEach(reportElement -> {
                //段落标题
                String paragraphTitle = reportElement.getShowName() != null ? reportElement.getShowName() : reportElement.getName();
                List<String> bindIds =getMatchOpinionByEventIdForDataBase(event.getEventId());
                if (reportElement.getName().equals("监测概述")) {
                    //获取各类信息总数
                    OpTypeNumVM opTypeDaysNum = publicOpinionService.getTypeNumEvent(event.getEventId(),null,bindIds);
                    String des = "监测主题相关信息内容0条。";
                    DecimalFormat df = new DecimalFormat("0.00");
                    if (opTypeDaysNum.getAllNum() != 0) {
                        des = "监测主题相关信息内容" + opTypeDaysNum.getAllNum() + "条。其中" +
                                "正面" + opTypeDaysNum.getPositive() +
                                "条，正面占比" + (df.format(((float) opTypeDaysNum.getPositive() / opTypeDaysNum.getAllNum()) * 100)) + "%，" +
                                "中性" + opTypeDaysNum.getNeutral() +
                                "条，中性占比" + (df.format(((float) opTypeDaysNum.getNeutral() / opTypeDaysNum.getAllNum()) * 100)) + "%，" +
                                "负面" + opTypeDaysNum.getNegative() +
                                "条，负面占比" + (df.format(((float) opTypeDaysNum.getNegative() / opTypeDaysNum.getAllNum()) * 100)) + "%。";
                    }
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setText(des);
                    contents.add(source);

                } else if (reportElement.getName().equals("事件简介")) {
                    //获取各类信息总数
                    List<NameValue> values = publicOpinionService.getMediaNameNum(event.getEventId(), null, bindIds);
                    long counts =publicOpinionService.getAllOpinionCount(event,null,bindIds);
                    StringBuffer sbName = new StringBuffer();
                    int indexMax = 0;
                    int valueMax = 0;
                    for (int i = 0; i < values.size(); i++) {
                        if (1 == 0) {
                            sbName.append(values.get(i).getName());
                        } else {
                            sbName.append("、" + values.get(i).getName());
                        }
                        //判断影响力最大的媒体
                        if (values.get(i).getValue() > valueMax) {
                            indexMax = i;
                            valueMax = values.get(i).getValue();
                        }
                    }
                    String des = "本报告针对" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startDate) +
                            "至" +
                            DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, finalEndDate) +
                            "时间范围内，互联网上的相关舆论数据进行了分析。文章分析关键词包括" + event.getRelatedWords() +
                            "。在分析时间范围内，共有" + counts +
                            "篇相关文章。舆论主要集中在境内，主要来源于" + sbName.toString() +
                            "等几大网站，" + values.get(indexMax).getName() +
                            "类型的相关舆论最多。详细报告如下：";
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setText(des);
                    contents.add(source);

                } else if (reportElement.getName().equals("本期导读")) {
                    //获取各类信息总数
                    String des = "根据对各大媒体新闻报道的跟进监测，现对根据对各大媒体新闻报道的跟进监测，现对" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startDate) + "至" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, finalEndDate) + "重要舆情进行汇总，谨供参阅";
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setText(des);
                    contents.add(source);

                } else if (reportElement.getName().equals("简报概述")) {
                    List<NameValue> values = publicOpinionService.getMediaNameNum(event.getEventId(), null, bindIds);
                    String des = "本报告就相关的文章进行分析，共有0篇相关素材。";
                    int sum = 0;
                    StringBuffer sbName = new StringBuffer();
                    StringBuffer sbMax = new StringBuffer();
                    StringBuffer sbPercentage = new StringBuffer();
                    int indexMax = 0;
                    int valueMax = 0;
                    sbName.append("目前主要的报道集中在");
                    for (int i = 0; i < values.size(); i++) {
                        sum += values.get(i).getValue();
                        if (1 == 0) {
                            sbName.append(values.get(i).getName());
                        } else {
                            sbName.append("、" + values.get(i).getName());
                        }
                        //判断影响力最大的媒体
                        if (values.get(i).getValue() > valueMax) {
                            indexMax = i;
                            valueMax = values.get(i).getValue();
                        }
                    }
                    sbPercentage.append("其中");
                    DecimalFormat df = new DecimalFormat("0.00");
                    for (int i = 0; i < values.size(); i++) {
                        String pe = df.format((float) values.get(i).getValue() / sum * 100);
                        sbPercentage.append(values.get(i).getName() + values.get(i).getValue() + "篇，" + "占比" + pe + "%，");
                    }

                    if (sum > 0) {
                        sbMax.append("而" + values.get(indexMax).getName() + "的比重最大，共有" + values.get(indexMax).getValue() + "篇，达到信息总量的" + df.format(((float) values.get(indexMax).getValue() / sum) * 100) + "%。");
                        sbName.append("等媒体，");
                        des = "本报告就相关的文章进行分析，共有" + sum + "篇相关素材。" +
                                sbName.toString() +
                                sbPercentage.toString() +
                                sbMax.toString() +
                                "详细报告请继续浏览";
                    }

                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setText(des);
                    contents.add(source);
                } else if (reportElement.getName().equals("处置建议")) {
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setText(reportElement.getShowText());
                    contents.add(source);
                } else if (reportElement.getName().equals("高频词云") && mapBase64.get("hotWords") != null) {
                    String imageBase64 = mapBase64.get("hotWords").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("来源类型分析") && mapBase64.get("sourceTypeAnalysis") != null) {
                    String imageBase64 = mapBase64.get("sourceTypeAnalysis").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("信息情感分布") && mapBase64.get("informationEmotionDistribution") != null) {
                    String imageBase64 = mapBase64.get("informationEmotionDistribution").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("载体情感分析") && mapBase64.get("carrierEmotionAnalysis") != null) {
                    String imageBase64 = mapBase64.get("carrierEmotionAnalysis").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("媒体来源明细") && mapBase64.get("mediaSourceDetails") != null) {
                    String imageBase64 = mapBase64.get("mediaSourceDetails").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("主要舆情")) {
                    List<PoPublicOpinion> opinions = getMainPublicOpinion(event.getEventId(),20);
                    List<HashMap<String, String>> list = new ArrayList<>();
                    for (int i = 0; i < opinions.size(); i++) {
                        String sensitive="";
                        if(opinions.get(i).getIspositive()==1){
                            sensitive="正面";
                        }else if(opinions.get(i).getIsneutral()==1){
                            sensitive="中性";
                        }else if(opinions.get(i).getIsnegative()==1){
                            sensitive="负面";
                        }
                        HashMap<String, String> map = new HashMap<>();
                        map.put("序号", String.valueOf(i + 1));
                        String title;
                        if (opinions.get(i).getTitle().length() > 50) {
                            title = opinions.get(i).getTitle().substring(0, 50);
                        } else {
                            title = opinions.get(i).getTitle();
                        }
                        map.put("标题", title + "\n" + (opinions.get(i).getUrl() != null ? opinions.get(i).getUrl() : ""));
                        String source= StringUtils.isNotEmpty(opinions.get(i).getMediaName())?opinions.get(i).getMediaName():(StringUtils.isNotEmpty(opinions.get(i).getAuthor())?opinions.get(i).getAuthor():opinions.get(i).getMediaType());
                        String date=opinions.get(i).getPublishDate()!=null? DateUtils.parseDateToStr("yyyy-MM-dd",opinions.get(i).getPublishDate()):opinions.get(i).getPublishDay();
                        map.put("日期与来源",  date + "\n" + source);
                        map.put("属性", sensitive);

                        list.add(map);
                    }
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setTable(list);
                    source.setStyle(ArticleStyleEnum.MainPublicOpinion.value);
                    contents.add(source);
                } else if (reportElement.getName().equals("舆情导读")) {
                    List<PoPublicOpinion> opinions = getGuideToReadingPublicOpinion(event.getEventId(),20);
                    List<HashMap<String, String>> list = new ArrayList<>();
                    for (int i = 0; i < opinions.size(); i++) {
                        String sensitive="";
                        if(opinions.get(i).getIspositive()==1){
                            sensitive="正面";
                        }else if(opinions.get(i).getIsneutral()==1){
                            sensitive="中性";
                        }else if(opinions.get(i).getIsnegative()==1){
                            sensitive="负面";
                        }
                        HashMap<String, String> map = new HashMap<>();
                        map.put("序号", String.valueOf(i + 1));
                        map.put("属性", sensitive);
                        String title;
                        if (opinions.get(i).getTitle().length() > 50) {
                            title = opinions.get(i).getTitle().substring(0, 50);
                        } else {
                            title = opinions.get(i).getTitle();
                        }
                        map.put("标题", title);
                        String source=StringUtils.isNotEmpty(opinions.get(i).getMediaName())?opinions.get(i).getMediaName():(StringUtils.isNotEmpty(opinions.get(i).getAuthor())?opinions.get(i).getAuthor():opinions.get(i).getMediaType());
                        map.put("来源", source);
                        map.put("链接", opinions.get(i).getUrl() != null ? opinions.get(i).getUrl() : "");
                        String date=opinions.get(i).getPublishDate()!=null? DateUtils.parseDateToStr("yyyy-MM-dd",opinions.get(i).getPublishDate()):opinions.get(i).getPublishDay();
                        map.put("日期", date);
                        map.put("内容", opinions.get(i).getSummary());
                        list.add(map);
                    }
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setTable(list);
                    source.setStyle(ArticleStyleEnum.PublicOpinionGuide.value);
                    contents.add(source);
                } else if (reportElement.getName().equals("事件脉络")) {
                    List<PoPublicOpinion> opinions = publicOpinionService.selectPoPublicOpinionListEventId(event.getEventId());
                    List<HashMap<String, String>> list = new ArrayList<>();
                    for (int i = 0; i < opinions.size(); i++) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("序号", String.valueOf(i + 1));
                        String title;
                        if (opinions.get(i).getTitle().length() > 50) {
                            title = opinions.get(i).getTitle().substring(0, 50);
                        } else {
                            title = opinions.get(i).getTitle();
                        }
                        map.put("标题", title);
                        String source=StringUtils.isNotEmpty(opinions.get(i).getMediaName())?opinions.get(i).getMediaName():(StringUtils.isNotEmpty(opinions.get(i).getAuthor())?opinions.get(i).getAuthor():opinions.get(i).getMediaType());
                        map.put("来源", source);
                        String date=opinions.get(i).getPublishDate()!=null? DateUtils.parseDateToStr("yyyy-MM-dd",opinions.get(i).getPublishDate()):opinions.get(i).getPublishDay();
                        map.put("日期", date);
                        map.put("内容", opinions.get(i).getTitle());
                        list.add(map);
                    }
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setTable(list);
                    source.setStyle(ArticleStyleEnum.VenationOfTheEvent.value);
                    contents.add(source);
                } else if (reportElement.getName().equals("热门文章")) {
                    PageInfo<PoPublicOpinion> pageInfo = publicOpinionService.hotPublicOpinion(event.getEventId(), null, null, 10,1, null);
                    List<PoPublicOpinion> opinions =pageInfo.getList();
                    List<HashMap<String, String>> list = new ArrayList<>();
                    for (int i = 0; i < opinions.size(); i++) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("序号", String.valueOf(i + 1));
                        String title;
                        if (opinions.get(i).getTitle().length() > 50) {
                            title = opinions.get(i).getTitle().substring(0, 50);
                        } else {
                            title = opinions.get(i).getTitle();
                        }
                        map.put("标题", title);
                        String source=StringUtils.isNotEmpty(opinions.get(i).getMediaName())?opinions.get(i).getMediaName():(StringUtils.isNotEmpty(opinions.get(i).getAuthor())?opinions.get(i).getAuthor():opinions.get(i).getMediaType());
                        map.put("来源", source);
                        String date=opinions.get(i).getPublishDate()!=null? DateUtils.parseDateToStr("yyyy-MM-dd",opinions.get(i).getPublishDate()):opinions.get(i).getPublishDay();
                        map.put("日期", date);
                        map.put("内容", opinions.get(i).getTitle());
                        list.add(map);
                    }
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setTable(list);
                    source.setStyle(ArticleStyleEnum.VenationOfTheEvent.value);
                    contents.add(source);
                } else if (reportElement.getName().equals("信息走势图") && mapBase64.get("informationTrend") != null) {
                    String imageBase64 = mapBase64.get("informationTrend").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("情感分析") && mapBase64.get("emotionalAnalysis") != null) {
                    String imageBase64 = mapBase64.get("emotionalAnalysis").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("首发媒体溯源")) {
                    List<PoPublicOpinion> opinions = publicOpinionService.getStartingMedia(event.getEventId(), null, bindIds);
                    List<HashMap<String, String>> list = new ArrayList<>();
                    for (int i = 0; i < opinions.size(); i++) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("媒体类型", opinions.get(i).getMediaType());
                        String title;
                        if (opinions.get(i).getTitle().length() > 50) {
                            title = opinions.get(i).getTitle().substring(0, 50);
                        } else {
                            title = opinions.get(i).getTitle();
                        }
                        map.put("标题", title);
                        String date=opinions.get(i).getPublishDate()!=null? DateUtils.parseDateToStr("yyyy-MM-dd",opinions.get(i).getPublishDate()):opinions.get(i).getPublishDay();
                        map.put("发布时间", date);
                        String source=StringUtils.isNotEmpty(opinions.get(i).getMediaName())?opinions.get(i).getMediaName():(StringUtils.isNotEmpty(opinions.get(i).getAuthor())?opinions.get(i).getAuthor():opinions.get(i).getMediaType());
                        map.put("信息来源", source);
                        list.add(map);
                    }
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setTable(list);
                    source.setStyle(ArticleStyleEnum.StartingMediaTracing.value);
                    contents.add(source);
                } else if (reportElement.getName().equals("媒体传播分析") && mapBase64.get("mediaCommunicationAnalysis") != null) {
                    String imageBase64 = mapBase64.get("mediaCommunicationAnalysis").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("信息载体趋势") && mapBase64.get("informationCarrierTrends") != null) {
                    String imageBase64 = mapBase64.get("informationCarrierTrends").split(",")[1];
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setImagePath(ImageUtils.GenerateImagePath(imageBase64, phantomjsSavePath,null));
                    contents.add(source);
                } else if (reportElement.getName().equals("文本")) {
                    ReportSource source = new ReportSource();
                    source.setTitle(paragraphTitle);
                    source.setText(reportElement.getText());
                    contents.add(source);
                }
            });

        }
        return contents;
    }


    @Override
    public List<PoPublicOpinion> getMainPublicOpinion(Long eventId, int i) {
        PublicOpinionEvents event = selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder sourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null);
        return esUtil.getMainPublicOpinion(sourceBuilder,i);
    }



    @Override
    public List<NameValue> getEventTypeCount() {
        return publicOpinionEventsMapper.getEventTypeCount();
    }

    @Override
    public int insertPoEventOpinionRelation(PoEventOpinionRelation poEventOpinionRelation) {
        return publicOpinionEventsMapper.insertPoEventOpinionRelation(poEventOpinionRelation);
    }

    @Override
    public List<String> selectOpinionIdsByEventRelation(PoEventOpinionRelation poEventOpinionRelation) {
        return publicOpinionEventsMapper.selectOpinionIdsByEventRelation(poEventOpinionRelation);
    }

    @Override
    public int setOpinionEventRelation(PoEventOpinionRelation poEventOpinionRelation) {
        List<PoEventOpinionRelation> list= publicOpinionEventsMapper.selectPoEventOpinionRelationList(poEventOpinionRelation);
        if(list.size()>0){
            List<Long> ids=new ArrayList<>();
            for (PoEventOpinionRelation p:list) {
                ids.add(p.getId());
            }
            publicOpinionEventsMapper.deletePoEventOpinionRelationByIds(ids.toArray(new Long[ids.size()]));
        }
        return publicOpinionEventsMapper.insertPoEventOpinionRelation(poEventOpinionRelation);
    }

    @Override
    @Transient
    public int setRelationBatchEventRelation(String[] ids, String type, Long eventId) {
        List<PoEventOpinionRelation> list=new ArrayList<>();
        for (int i = 0; i <ids.length ; i++) {
            PoEventOpinionRelation p=new PoEventOpinionRelation();
            p.setOpinionId(ids[i]);
            p.setRelation(type);
            p.setEventId(eventId);
            list.add(p);
        }
        list.forEach(poEventOpinionRelation -> {
            setOpinionEventRelation(poEventOpinionRelation);
        });
        return 0;
    }

    @Override
    public List<NameListValue> getSentimentByPublishTimeByEventId(Long eventId) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByPublishDateSentiment(searchSourceBuilder);
    }

    @Override
    public List<NameListValue> getMediaTypeByPublishTimeByEventId(Long eventId) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByPublishDateAndMediaType(searchSourceBuilder);
    }


    @Override
    public List<PoPublicOpinion> getFirstMediaReleasedByEventId(Long eventId) {
        //绑定的舆情
        List<String> bindIds =getMatchOpinionByEventIdForDataBase(eventId);
        //首发媒体
        List<PoPublicOpinion> startingMedia=publicOpinionService.getStartingMedia(eventId,null ,bindIds);
        return startingMedia;
    }

    @Override
    public List<NameListValue> getMediaTypeSensitiveDayNumEvent(Long eventId) {
        //绑定的舆情
        List<String> bindIds =getMatchOpinionByEventIdForDataBase(eventId);
        //首发媒体
        List<NameListValue> mediaTypeSensitive =publicOpinionService.getMediaTypeSensitiveDayNumEvent(eventId,null ,bindIds);
        return mediaTypeSensitive;
    }

    @Override
    public List<OpMediaNameSensitiveDayNumVM> countSensitiveOpinionByMediaName(Long eventId) {
        //绑定的舆情
        List<String> bindIds =getMatchOpinionByEventIdForDataBase(eventId);
        //首发媒体
        List<OpMediaNameSensitiveDayNumVM> mediaTypeSensitive =publicOpinionService.countSensitiveOpinionByMediaName(eventId,null ,bindIds);
        return mediaTypeSensitive;
    }

    @Override
    public List<OpAuthorSensitiveDayNumVM> countSensitiveAuthorOpinion(Long eventId) {
        //绑定的舆情
        List<String> bindIds =getMatchOpinionByEventIdForDataBase(eventId);
        //首发媒体
        List<OpAuthorSensitiveDayNumVM> mediaTypeSensitive =publicOpinionService.countSensitiveAuthorOpinion(eventId,null ,bindIds);
        return mediaTypeSensitive;
    }


    @Override
    public List<NameValue> getKeywordsByEventId(Long eventId, int i) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByKeywords(searchSourceBuilder, i);
    }


    @Override
    public List<PoPublicOpinion> getViewpointAnalysis(Long eventId) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        //绑定的舆情
        List<String> bindIds =getMatchOpinionByEventIdForDataBase(eventId);
        //正负面观点分析
        List<PoPublicOpinion> viewpointAnalysis=publicOpinionService.getViewpointAnalysis(event,null,bindIds);
        return viewpointAnalysis;
    }


    @Override
    public List<NameValue> getPublicOpinionCountGroupByProvinceOfEventId(Long eventId) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByProvince(searchSourceBuilder);
    }

    @Override
    public List<NameValue> getPublicOpinionCountGroupByDayOfEventId(Long eventId) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByPublishDate(searchSourceBuilder);
    }

    @Override
    public List<NameValue> getPersonsByEventId(Long eventId, int i) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByRelationPersonName(searchSourceBuilder, i);
    }

    @Override
    public List<NameValue> getOrganizationsByEventId(Long eventId, int i) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByRelationOrganizationName(searchSourceBuilder, i);
    }

    @Override
    public List<NameValue> getLocationsByEventId(Long eventId, int i) {
        PublicOpinionEvents event = publicOpinionEventsMapper.selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder searchSourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null, null);
        return esUtil.getCountGroupByRelationLocationName(searchSourceBuilder, i);
    }

    /**
     * 舆情导读
     * @param eventId
     * @param i
     * @return
     */
    @Override
    public List<PoPublicOpinion> getGuideToReadingPublicOpinion(Long eventId, int i) {
        PublicOpinionEvents event = selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder sourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null);
        return esUtil.getMainPublicOpinion(sourceBuilder,i);
    }

    /**
     * 信息总览
     * @param eventId
     * @return
     */
    @Override
    public OpTypeNumVM getAllInformation(Long eventId) {
        //获取各类信息总数
        OpTypeNumVM opTypeDaysNum = publicOpinionService.getTypeNumEvent(eventId,null,null);
        return opTypeDaysNum;
    }


    @Override
    public List<NameListValue> groupSensitiveOpinionDayHour(String name, PublicOpinionEvents event, EventParameterVo parameter, List<String> bindIds) {
        if (parameter == null) {
            parameter = new EventParameterVo();
        }
        parameter.setIsnegative(1);
        //构建查询语句
        SearchSourceBuilder sourceBuilder = esUtil.buildSearchSourceBuilder(event, parameter, bindIds);
        try {
            return esUtil.getCountGroupByPublishDateAndPublishTime(sourceBuilder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map<String, Object> getEventSummary(Long eventId) {
        PublicOpinionEvents event = selectPublicOpinionEventsById(eventId);
        SearchSourceBuilder sourceBuilder = esUtil.buildSearchSourceBuilder(event, null, null);
        return esUtil.getEventSummary(sourceBuilder);
    }

}
